//
//  UserInfoController.m
//  suyuanDemo
//
//  Created by 徐宜硕 on 15/9/22.
//  Copyright © 2015年 Xshuo. All rights reserved.
//

#import "UserInfoController.h"
#import "Json.h"
#import "Sysconfig.h"
#import "HttpClient.h"
#import "TestController.h"
#import "ModifySexController.h"
@interface UserInfoController ()<UIActionSheetDelegate,UIPickerViewDataSource,UIPickerViewDelegate>
@property (nonatomic, strong) UIView *dateView;
@property (nonatomic, strong) UIDatePicker *datePicker;
@property (nonatomic, strong) UIButton *complete;
@property (nonatomic, strong) UIButton *cancelButton;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) NSArray *areaArray;

@end

@implementation UserInfoController

- (NSArray *)areaArray {
    if (_areaArray == nil) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"area" ofType:@"plist"];
        NSArray *array = [NSArray arrayWithContentsOfFile:path];
        NSMutableArray *tempArray = [NSMutableArray array];
        for (int i = 0; i<array.count; i++) {
            
        }
    }
    return _areaArray;
}

- (void)createDatePicker {
    CGFloat viewH = 200;
    self.dateView = [[UIView alloc]init];
    self.dateView.frame = CGRectMake(0, 0, sizeW, sizeH+50);
    [self.view addSubview:self.dateView];
    
    self.datePicker = [[UIDatePicker alloc] init];
    self.datePicker.frame = CGRectMake(0, sizeH - viewH, sizeW, viewH);
    self.datePicker.backgroundColor = [UIColor whiteColor];
    self.datePicker.datePickerMode = UIDatePickerModeDate;
    [self.dateView addSubview:self.datePicker];
    
    self.complete = [[UIButton alloc] init];
    self.complete.frame = CGRectMake(sizeW - 60, sizeH - viewH-30, 60, 30);
    [self.complete setTitle:@"test" forState:UIControlStateNormal];
    self.complete.backgroundColor = [UIColor redColor];
    self.complete.opaque = YES;
    self.complete.clipsToBounds = YES;
    self.complete.layer.cornerRadius = 8;
    [self.complete addTarget:self action:@selector(completeBrnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.dateView addSubview:self.complete];
    
    self.cancelButton = [[UIButton alloc] init];
    self.cancelButton.frame = CGRectMake(0, sizeH - viewH - 30, 60, 30);
    [self.cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    self.cancelButton.backgroundColor = [UIColor redColor];
    self.cancelButton.opaque = YES;
    self.cancelButton.clipsToBounds = YES;
    self.cancelButton.layer.cornerRadius = 8;
    [self.cancelButton addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.dateView addSubview:self.cancelButton];
}
- (void)cancelBtnClick {
    [self.cancelButton setEnabled:YES];
    NSLog(@"test success");
    self.dateView.hidden = YES;
//    [self.navigationController popViewControllerAnimated:NO];
}

- (void)completeBrnClick {
    [self.complete setEnabled:YES];
    NSLog(@"测试成功");
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateString = [formatter stringFromDate:self.datePicker.date];
    self.birthdayLabel.text = dateString;
    self.dateView.hidden = YES;
    
}

- (void)locationSelect {
    NSLog(@"dds");
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self headimage];
    
    self.nameLabel.text = [self tableCellModifyWithKey:@"nickname"];
    
    self.phoneLaebl.text = [self tableCellModifyWithKey:@"phone"];
    
    self.sexLabel.text = [self tableCellModifyWithKey:@"sex"];
    
    self.birthdayLabel.text = [self tableCellModifyWithKey:@"birthday"];
    
    [self.delegate modifyHeadImage:self.imageView.image];
    
    
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSex:) name:@"SaveSex" object:nil];
//    [self headImageUpLoad];

}

- (void)testBirthday {
    
    NSString *dateStr = [self tableCellModifyWithKey:@"birthday"];
    
    int dateInt = [dateStr intValue];
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:dateInt];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *destDateString = [formatter stringFromDate:date];
    
    self.birthdayLabel.text = destDateString;
    
}

#pragma mark 连接数据库
//- (void)headImageUpLoad {
//    
//    NSString *userid = [self tableCellModifyWithKey:@"userid"];
//    NSString *token = [self tableCellModifyWithKey:@"token"];
//    NSString *password = [self tableCellModifyWithKey:@"password"];
//    
//    NSDictionary *parameters = @{@"userid":userid,@"token":token,@"passwd":password,@"type":@"updateuserpic"};
//    
//    [[[HttpClient alloc]getAFHTTPRequestOperationManager] POST:[[Sysconfig alloc] getServerAddress:@"Api_UserInfo"] parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//        NSLog(@"连接成功");
//        // 获取数据成功  解析JSON数据
//        Json *json = [[Json alloc] init];
//        if ([[json getrootValue:@"returncode"] isEqualToString:@"0"]) {
//            NSLog(@"%@",[json getrootValue:@"message"]);
//        }
//        
//    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
//        NSLog(@"连接失败");
//    }];
//}

#pragma mark 封装调用本地缓存图像方法
- (void)headimage {
    
    // NSUserDefaults 取出本地存储的url
    NSUserDefaults *picDefualts = [NSUserDefaults standardUserDefaults];
    NSString *picURLStr = [picDefualts objectForKey:@"picurl"];
    // 与数据库接口合并
    NSString *picHttp = [NSString stringWithFormat:@"%@%@",top,picURLStr];
    NSURL *picurl = [NSURL URLWithString:picHttp];
    NSData *data = [NSData dataWithContentsOfURL:picurl];
    self.imageView.image = [UIImage imageWithData:data];
    // 切圆角
    self.imageView.layer.cornerRadius = 8;
    self.imageView.clipsToBounds= YES;
    // 设置边框
    self.imageView.layer.borderColor = [UIColor blackColor].CGColor;
    self.imageView.layer.borderWidth = 0.8;
    
}

#pragma mark 封装调用本地数据方法
- (NSString *)tableCellModifyWithKey:(NSString *)key {
    
    NSUserDefaults *userDefualts = [NSUserDefaults standardUserDefaults];
    NSString *defualtStr = [userDefualts objectForKey:key];
    return defualtStr;
    
}


#pragma mark  选中cell时做的事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        [self startChoosePhoto];
    }else if (indexPath.row == 1) {
        
        NSString *name = [self tableCellModifyWithKey:@"nickname"];
        [self performSegueWithIdentifier:@"testSegue" sender:name];
        
    }else if (indexPath.row == 3) {
        
        NSString *sex = [self tableCellModifyWithKey:@"sex"];
        [self performSegueWithIdentifier:@"sexSegue" sender:sex];
        
    }else if (indexPath.row == 4) {
        
        [self createDatePicker];
    }else if (indexPath.row == 5) {
        NSLog(@"地址选择器");
    }
}

#pragma mark 跳转之前的方法
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"testSegue"]) {
        
        TestController *testVC = segue.destinationViewController;
        testVC.name = (NSString *)sender;
        
    }else if ([segue.identifier isEqualToString:@"sexSegue"]) {
        
        ModifySexController *sexVC = segue.destinationViewController;
        sexVC.sex = (NSString *)sender;
        
    }
}


#pragma mark 调用相机和相册
//开始创建actionSheet
- (void)startChoosePhoto {
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.view];
}

// actionSheet的代理方法，用来设置每个按钮点击的触发事件
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //构建图像选择器
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    
    [pickerController setDelegate:(id)self];
    
    if (buttonIndex == 0) {
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        }
        [pickerController.view setTag:actionSheet.tag];
        [self presentViewController:pickerController animated:YES completion:nil];
    }
    else if(buttonIndex == 1){
        pickerController.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:pickerController animated:YES completion:nil];
    }
    else{
        [actionSheet setHidden:YES];
    }
}

// 图像选择器选取好后，将图片数据拿过来
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage* image = [info objectForKey: @"UIImagePickerControllerOriginalImage"];
    NSData *imgData = UIImageJPEGRepresentation(image, 0.5);
    self.imageView.image = [UIImage imageWithData:imgData];
    [self.tableView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
